import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:intl/intl.dart'; // 导入intl包
import '../../../common/utils/toast_util.dart';
import '../../../common/services/user_service.dart';
import '../../../common/services/native_wechat_share_service.dart';
import '../../../common/routers/names.dart';
import '../../../common/utils/map_launcher_util.dart';
import '../../../common/api/activity_api.dart';
import '../../../common/api/friend_api.dart';
import '../../../common/api/user_api.dart';
import '../../../common/utils/encryption_util.dart';
import '../../../common/utils/permission_util.dart'; // 🎯 权限计算工具
import '../../../common/services/http.dart';
import '../../../common/models/index.dart'; // 添加ActivityModel支持
import '../../play/plays/models/post_model.dart';
import 'dart:developer' as developer;

/// 首页活动详情底部弹出框组件
/// 
/// 用于显示活动的详细信息，包含：
/// - 活动图片展示（支持多图切换）
/// - 用户信息展示（头像、昵称、守护者标签）
/// - 活动详情信息（标题、地址、时间、参与人数等）
/// - 交互功能（点赞、分享、举报、加好友、加入活动）
class ActivityDetailBottomSheet extends StatefulWidget {
  // 活动数据
  final PostModel activity;
  // 加入成功的回调
  final VoidCallback? onJoinSuccess;

  const ActivityDetailBottomSheet({
    Key? key,
    required this.activity,
    this.onJoinSuccess,
  }) : super(key: key);

  /// 显示底部详情框的静态方法
  static Future<void> show({
    required PostModel activity,
    VoidCallback? onJoinSuccess, // 加入成功的回调
  }) {
    return Get.bottomSheet(
      // 使用 MediaQuery.removePadding 移除底部 padding
      MediaQuery.removePadding(
        context: Get.context!,
        removeBottom: true,
        child: ActivityDetailBottomSheet(
          activity: activity,
          onJoinSuccess: onJoinSuccess,
        ),
      ),
      backgroundColor: Colors.white,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      isScrollControlled: true, // 允许内容滚动
      clipBehavior: Clip.antiAlias,
      enableDrag: true, 
      isDismissible: true, 
    );
  }

  @override
  State<ActivityDetailBottomSheet> createState() => _ActivityDetailBottomSheetState();
}

class _ActivityDetailBottomSheetState extends State<ActivityDetailBottomSheet> {
  // 获取UserService实例
  final UserService userService = UserService.to;
  
  // 图片切换相关
  late PageController _imagePageController;
  int _currentImageIndex = 0;
  
  // 活动状态
  bool isJoined = false;
  int joinedCount = 0;
  
  // 发送状态控制
  bool _isJoining = false;
  
  // 好友关系相关状态
  bool _isCheckingFriendship = true; // 是否正在检查好友关系
  bool _isFriend = false; // 是否已经是好友
  bool _isAddingFriend = false; // 是否正在发送好友申请
  
  @override
  void initState() {
    super.initState();
    _imagePageController = PageController();
    
    // 🔥 输出活动详情信息到控制台

    
    // 解析参与人数
    _parseJoinedCount();
    
    // 检查好友关系
    _checkFriendRelationship();
  }
  
  @override
  void dispose() {
    _imagePageController.dispose();
    super.dispose();
  }
  
  // 判断是否是当前用户的活动
  bool get isCurrentUserActivity {
    final currentUser = userService.currentUser;
    if (currentUser == null) return false;
    
    // 如果活动作者名称匹配当前用户昵称，认为是当前用户的活动
    return widget.activity.authorName == currentUser.username;
  }
  

  
  /// 解析参与人数（优先使用timeAgo字段，因为活动列表显示的是准确的）
  void _parseJoinedCount() {
    try {
      // 🎯 优先从timeAgo解析人数信息（与活动列表保持一致）
      if (widget.activity.timeAgo.contains('/')) {
        final parts = widget.activity.timeAgo.split('/');
        if (parts.length >= 2) {
          joinedCount = int.tryParse(parts[0]) ?? 0;
          developer.log('📊 从timeAgo解析参与人数: ${parts[0]}/${parts[1]}');
          return;
        }
      }
      
      // 兜底：如果timeAgo解析失败，使用currentParticipants字段
      if (widget.activity.currentParticipants != null) {
        joinedCount = widget.activity.currentParticipants!;
        developer.log('📊 使用currentParticipants字段: $joinedCount');
      } else {
        joinedCount = 0;
        developer.log('⚠️ 无法获取参与人数，设为0');
      }
    } catch (e) {
      developer.log('⚠️ 解析参与人数失败: $e');
      joinedCount = 0;
    }
  }

  void _showReportDialog() {
    final TextEditingController reportController = TextEditingController();
    String selectedReason = '';
    
    Get.dialog(
      StatefulBuilder(
        builder: (context, setState) {
          return Dialog(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
            child: Container(
              padding: const EdgeInsets.all(20),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Center(
                    child: Text(
                      '举报原因',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  const SizedBox(height: 20),
                  Container(
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: Colors.grey[200],
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: TextField(
                      controller: reportController,
                      maxLines: 4,
                      decoration: const InputDecoration(
                        hintText: '输入举报原因',
                        border: InputBorder.none,
                        hintStyle: TextStyle(color: Colors.grey),
                      ),
                    ),
                  ),
                  const SizedBox(height: 16),
                  Wrap(
                    spacing: 8,
                    runSpacing: 8,
                    children: [
                      _buildReasonChip('爽约未到场', selectedReason, (reason) {
                        setState(() {
                          selectedReason = reason;
                        });
                      }),
                      _buildReasonChip('骂人', selectedReason, (reason) {
                        setState(() {
                          selectedReason = reason;
                        });
                      }),
                      _buildReasonChip('中途开溜', selectedReason, (reason) {
                        setState(() {
                          selectedReason = reason;
                        });
                      }),
                      _buildReasonChip('品行不端', selectedReason, (reason) {
                        setState(() {
                          selectedReason = reason;
                        });
                      }),
                      _buildReasonChip('吃的太多', selectedReason, (reason) {
                        setState(() {
                          selectedReason = reason;
                        });
                      }),
                    ],
                  ),
                  const SizedBox(height: 24),
                  SizedBox(
                    width: double.infinity,
                    child: ElevatedButton(
                      onPressed: () async {
                        String reportText = reportController.text.trim();
                        if (selectedReason.isNotEmpty) {
                          reportText = selectedReason + (reportText.isNotEmpty ? ': $reportText' : '');
                        }
                        
                        if (reportText.isNotEmpty) {
                          Get.back(); // 先关闭对话框
                          await _submitReport(reportText, selectedReason);
                        } else {
                          ToastUtil.warning('请输入举报原因或选择预设选项');
                        }
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: const Color(0xFFE33641),
                        padding: const EdgeInsets.symmetric(vertical: 12),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                      ),
                      child: const Text(
                        '提交举报信息',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildReasonChip(String reason, String selectedReason, Function(String) onTap) {
    bool isSelected = selectedReason == reason;
    return GestureDetector(
      onTap: () => onTap(reason),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        decoration: BoxDecoration(
          color: isSelected ? const Color(0xFFE33641) : Colors.grey[200],
          borderRadius: BorderRadius.circular(16),
        ),
        child: Text(
          reason,
          style: TextStyle(
            color: isSelected ? Colors.white : Colors.black87,
            fontSize: 14,
          ),
        ),
      ),
    );
  }

  /// 检查好友关系
  Future<void> _checkFriendRelationship() async {
    try {
      final userService = UserService.to;
      final currentUser = userService.currentUser;
      
      if (currentUser == null) {
        setState(() {
          _isCheckingFriendship = false;
          _isFriend = false;
        });
        return;
      }
      
      // 从PostModel中获取发布者ID
      int publisherId;
      developer.log('🔍 调试PostModel数据:');
      developer.log('📝 活动ID: ${widget.activity.id}');
      developer.log('📝 发布者名称: ${widget.activity.authorName}');
      developer.log('📝 发布者ID: ${widget.activity.authorId}');
      
      if (widget.activity.authorId != null) {
        // 🔥 优先使用PostModel中的authorId字段
        publisherId = widget.activity.authorId!;
        developer.log('✅ 从PostModel获取发布者ID: $publisherId');
      } else {
        // 🎯 兜底：跳过好友关系检查，假设不是好友
        developer.log('⚠️ PostModel中没有authorId字段，跳过好友关系检查');
        setState(() {
          _isCheckingFriendship = false;
          _isFriend = false; // 假设不是好友，显示加好友按钮
        });
        return;
      }
      
      // 如果是自己的活动，不需要检查好友关系
      if (publisherId == currentUser.userid) {
        setState(() {
          _isCheckingFriendship = false;
          _isFriend = true; // 设为true以隐藏加好友按钮
        });
        return;
      }
      
      developer.log('🔍 开始检查好友关系');
      developer.log('👤 当前用户ID: ${currentUser.userid}');
      developer.log('👤 活动发布者ID: $publisherId');
      
      // 调用好友关系检查API
      final response = await FriendApi.checkFriendRelationship(
        userId: currentUser.userid,
        targetUserId: publisherId,
      );
      
      if (response.isSuccess && response.data != null) {
        setState(() {
          _isFriend = response.data!.isFriend ?? false;
          _isCheckingFriendship = false;
        });
        
        developer.log('✅ 好友关系检查完成: ${_isFriend ? "已是好友" : "不是好友"}');
        developer.log('📊 好友关系详情:');
        developer.log('   - 关系类型: ${response.data!.relationshipType}');
        developer.log('   - 好友状态: ${response.data!.status}');
        developer.log('   - 是否好友: ${response.data!.isFriend}');
        developer.log('   - 好友关系ID: ${response.data!.friendshipId}');
      } else {
        setState(() {
          _isFriend = false;
          _isCheckingFriendship = false;
        });
        developer.log('⚠️ 好友关系检查失败: ${response.message}');
        developer.log('📊 响应状态: ${response.status}');
        developer.log('📊 响应数据: ${response.data}');
      }
      
    } catch (e) {
      developer.log('💥 检查好友关系异常: $e');
      setState(() {
        _isCheckingFriendship = false;
        _isFriend = false;
      });
    }
  }

  /// 发送好友申请
  Future<void> _addFriend() async {
    if (_isAddingFriend) return;
    
    try {
      setState(() {
        _isAddingFriend = true;
      });
      
      final userService = UserService.to;
      final currentUser = userService.currentUser;
      
      if (currentUser == null) {
        ToastUtil.error('请先登录');
        return;
      }
      
      // 获取发布者ID（与检查好友关系时的逻辑保持一致）
      int publisherId;
      if (widget.activity.authorId != null) {
        publisherId = widget.activity.authorId!;
      } else {
        ToastUtil.error('无法获取用户信息');
        return;
      }
      
      developer.log('🤝 开始发送好友申请');
      developer.log('👤 发送者ID: ${currentUser.userid}');
      developer.log('👤 接收者ID: $publisherId');
      
      // 调用发送好友申请API
      final response = await FriendApi.sendFriendRequest(
        senderId: currentUser.userid,
        receiverId: publisherId,
        message: '通过活动详情页发送的好友申请',
        free: PermissionUtil.calculateAddFriendFree(), // 🎯 动态计算加好友权限（模仿MyApplication2）
      );
      
      if (response.isSuccess) {
        // 🎯 增加加好友计数（模仿MyApplication2的逻辑）
        PermissionUtil.incrementAddFriendCount();
        
        ToastUtil.success('好友申请已发送！');
        developer.log('✅ 好友申请发送成功');
        
        // 发送成功后重新检查好友关系状态
        await _checkFriendRelationship();
      } else {
        if (response.message.contains('已经是好友') || response.message.contains('你们已经是好友了')) {
          // 🔥 已经是好友的情况，更新UI状态并显示友好提示
          setState(() {
            _isFriend = true;
          });
          ToastUtil.info('你们已经是好友了');
          developer.log('ℹ️ 好友关系状态: 已经是好友');
        } else if (response.message.contains('已经发送过好友申请') || 
            response.message.contains('请等待对方处理')) {
          ToastUtil.info(response.message);
          developer.log('ℹ️ 好友申请状态: ${response.message}');
        } else {
          ToastUtil.error('发送失败: ${response.message}');
          developer.log('❌ 好友申请发送失败: ${response.message}');
        }
      }
      
    } catch (e) {
      developer.log('💥 发送好友申请异常: $e');
      ToastUtil.error('发送好友申请失败');
    } finally {
      setState(() {
        _isAddingFriend = false;
      });
    }
  }

  /// 加入活动（调用真实API）
  void _joinActivity() async {
    if (isCurrentUserActivity) {
      ToastUtil.info('这是您发布的活动');
      return;
    }
    
    if (_isJoining) return;
    
    try {
      setState(() {
        _isJoining = true;
      });
      
      developer.log('🎯 准备加入活动');
      developer.log('📝 活动ID: ${widget.activity.id}');
      developer.log('🏷️ 活动标题: ${widget.activity.title}');

      // 获取当前用户信息
      final currentUser = userService.currentUser;
      if (currentUser == null) {
        ToastUtil.error('请先登录');
        return;
      }

      // 提取实际的活动ID（去掉前缀）
      final activityIdStr = widget.activity.id.replaceFirst('real_activity_', '');
      final activityId = int.tryParse(activityIdStr);
      
      if (activityId == null) {
        ToastUtil.error('活动ID格式错误');
        return;
      }

      // 🚀 调用真实的加入活动API
      final joinResponse = await ActivityApi.joinActivity(
        activityId: activityId,
        userId: currentUser.userid,
        userNickname: currentUser.username ?? '未知用户',
        userAvatarUrl: currentUser.userAvatarUrl,
        userSignature: currentUser.userSignature,
        userTags: currentUser.userTags,
        userPoints: currentUser.userPoints,
        participantStatus: '待审核',
      );

      // 处理API响应
      if (joinResponse.isSuccess) {
        setState(() {
          isJoined = !isJoined;
          joinedCount += isJoined ? 1 : -1;
        });
        
        if (isJoined) {
          ToastUtil.success('🎉 ${joinResponse.message}');
          developer.log('✅ 用户成功加入活动');
          
          // 🔥 发送融云活动申请推送消息
          try {
            await ActivityApi.sendRongCloudActivityRequestPush(
              activityId: activityId,
              activityTitle: widget.activity.title,
              activityPublisherId: widget.activity.authorId ?? 0,
              applicantUserId: currentUser.userid,
              applicantUserName: currentUser.username ?? '未知用户',
            );
            developer.log('✅ 活动申请融云推送发送完成');
          } catch (pushError) {
            developer.log('⚠️ 活动申请融云推送发送失败: $pushError');
            // 推送失败不影响主流程
          }
          
          // 🎯 调用成功回调，通知主界面更新状态
          if (widget.onJoinSuccess != null) {
            widget.onJoinSuccess!();
            developer.log('📞 已调用加入成功回调');
          }
        } else {
          ToastUtil.info('❌ 已退出活动');
          developer.log('❌ 用户退出活动');
        }
      } else {
        // 🎯 优化错误处理：检查是否为重复参加错误
        if (joinResponse.message.contains('已参加') || joinResponse.message.contains('重复参加')) {
          // 重复参加的情况，更新UI状态并调用回调
          setState(() {
            isJoined = true;
          });
          
          // 调用回调，通知主界面更新状态
          if (widget.onJoinSuccess != null) {
            widget.onJoinSuccess!();
            developer.log('📞 重复参加情况下调用回调');
          }
          
          // 直接显示服务器返回的消息
          ToastUtil.warning(joinResponse.message);
          developer.log('⚠️ 重复参加: ${joinResponse.message}');
        } else {
          // 其他错误情况
          ToastUtil.error('加入失败: ${joinResponse.message}');
          developer.log('❌ 加入活动失败: ${joinResponse.message}');
        }
      }
      
    } catch (e) {
      developer.log('💥 加入活动异常: $e');
      ToastUtil.error('加入活动失败: ${e.toString()}');
    } finally {
      setState(() {
        _isJoining = false;
      });
    }
  }
  
  /// 格式化活动时间（显示开始时间和结束时间）- 🔥 与MyApplication2保持一致
  String _getFormattedPublishTime() {
    try {
      developer.log('🕒 开始格式化活动时间');
      developer.log('📊 timeAgo字段: ${widget.activity.timeAgo}');
      developer.log('📊 activityPublishTime字段: ${widget.activity.activityPublishTime}');
      developer.log('📊 extraData.activityEndTime字段: ${widget.activity.extraData?.activityEndTime}');
      
      // 🔥 优先使用activityPublishTime字段（与MyApplication2一致）
      if (widget.activity.activityPublishTime != null && widget.activity.activityPublishTime!.isNotEmpty) {
        try {
          final startTimeStr = widget.activity.activityPublishTime!;
          developer.log('✅ 使用activityPublishTime字段: $startTimeStr');
          
          // 解析ISO格式时间（如"2025-08-27T15:01:00"）
          final startTime = DateTime.parse(startTimeStr);
          developer.log('✅ 成功解析活动开始时间: $startTime');
          
          // 格式化开始时间
          final formattedStartTime = _formatDateTime(startTime);
          
          // 🔥 检查是否有结束时间
          String formattedEndTime;
          final extraData = widget.activity.extraData; // 引入局部变量
          if (extraData?.activityEndTime?.isNotEmpty == true) { // 简化空安全检查
            // 有真实结束时间，使用它
            try {
              final endTime = DateFormat("yyyy-MM-dd H:mm").parse(extraData!.activityEndTime!); // 使用DateFormat解析
              formattedEndTime = _formatDateTime(endTime);
              developer.log('✅ 使用真实结束时间: ${extraData.activityEndTime}');
            } catch (e) {
              // 解析结束时间失败，计算默认结束时间（开始时间+2小时）
              final defaultEndTime = startTime.add(const Duration(hours: 2));
              formattedEndTime = _formatDateTime(defaultEndTime);
              developer.log('❌ 解析结束时间失败，使用默认结束时间(+2小时): $e');
            }
          } else {
            // 没有结束时间，计算默认结束时间（开始时间+2小时）
            final defaultEndTime = startTime.add(const Duration(hours: 2));
            formattedEndTime = _formatDateTime(defaultEndTime);
            developer.log('⚠️ 没有结束时间，使用默认结束时间(开始时间+2小时)');
          }
          
          final result = '$formattedStartTime---$formattedEndTime';
          developer.log('📅 格式化后的时间范围: $result');
          return result;
        } catch (e) {
          developer.log('❌ 解析activityPublishTime失败: $e，尝试兼容方案');
        }
      }
      
      // 🎯 兼容方案：如果没有activityPublishTime，尝试使用publishTime字段
      if (widget.activity.publishTime != null && widget.activity.publishTime!.isNotEmpty) {
        try {
          final publishTimeStr = widget.activity.publishTime!;
          developer.log('✅ 兼容模式：使用publishTime字段: $publishTimeStr');
          
          // 解析ISO格式时间
          final activityTime = DateTime.parse(publishTimeStr);
          developer.log('✅ 成功解析publishTime: $activityTime');
          
          // 格式化开始时间
          final formattedStartTime = _formatDateTime(activityTime);
          
          // 🔥 检查是否有结束时间
          String formattedEndTime;
          final extraData = widget.activity.extraData; // 引入局部变量
          if (extraData?.activityEndTime?.isNotEmpty == true) { // 简化空安全检查
            try {
              final endTime = DateFormat("yyyy-MM-dd H:mm").parse(extraData!.activityEndTime!); // 使用DateFormat解析
              formattedEndTime = _formatDateTime(endTime);
            } catch (e) {
              // 解析结束时间失败，计算默认结束时间（开始时间+2小时）
              final defaultEndTime = activityTime.add(const Duration(hours: 2));
              formattedEndTime = _formatDateTime(defaultEndTime);
            }
          } else {
            // 没有结束时间，计算默认结束时间（开始时间+2小时）
            final defaultEndTime = activityTime.add(const Duration(hours: 2));
            formattedEndTime = _formatDateTime(defaultEndTime);
          }
          
          final result = '$formattedStartTime---$formattedEndTime';
          developer.log('📅 兼容模式格式化时间范围: $result');
          return result;
        } catch (e) {
          developer.log('❌ 解析publishTime失败: $e，尝试其他方式');
        }
      }
      
      // 🎯 最终兜底方案：解析timeAgo字段中的ISO格式时间
      final timeStr = widget.activity.timeAgo;
      
      if (timeStr.contains('T') && timeStr.length >= 19) {
        // 解析ISO格式时间（如"2025-08-25T18:16:00"）
        try {
          final activityTime = DateTime.parse(timeStr);
          developer.log('✅ 从timeAgo成功解析活动时间: $activityTime');
          
          final formattedStartTime = _formatDateTime(activityTime);
          
          // 🔥 检查是否有结束时间
          String formattedEndTime;
          final extraData = widget.activity.extraData; // 引入局部变量
          if (extraData?.activityEndTime?.isNotEmpty == true) { // 简化空安全检查
            try {
              final endTime = DateFormat("yyyy-MM-dd H:mm").parse(extraData!.activityEndTime!); // 使用DateFormat解析
              formattedEndTime = _formatDateTime(endTime);
            } catch (e) {
              // 解析结束时间失败，计算默认结束时间（开始时间+2小时）
              final defaultEndTime = activityTime.add(const Duration(hours: 2));
              formattedEndTime = _formatDateTime(defaultEndTime);
            }
          } else {
            // 没有结束时间，计算默认结束时间（开始时间+2小时）
            final defaultEndTime = activityTime.add(const Duration(hours: 2));
            formattedEndTime = _formatDateTime(defaultEndTime);
          }
          
          final result = '$formattedStartTime---$formattedEndTime';
          developer.log('📅 从timeAgo格式化的时间范围: $result');
          return result;
        } catch (e) {
          developer.log('❌ 解析timeAgo中的ISO时间失败: $e');
        }
      } else if (timeStr.isNotEmpty && timeStr != '刚刚' && !timeStr.contains('/')) {
        // 处理其他格式的时间字符串（但跳过人数信息）
        developer.log('📝 使用原始timeAgo字符串: $timeStr');
        return timeStr;
      }
      
      // 🎯 最终兜底：如果所有方式都失败，显示时间待定
      developer.log('⚠️ 无法从任何源获取时间信息，显示默认提示');
      return '时间待定';
          
    } catch (e) {
      developer.log('💥 格式化活动时间异常: $e');
      return '时间待定';
    }
  }
  
  /// 格式化DateTime为字符串
  String _formatDateTime(DateTime dateTime) {
    // 使用 Intl.DateFormat 来格式化日期时间，确保一致性
    return DateFormat('yyyy-MM-dd HH:mm:ss').format(dateTime);
  }
  
  /// 🔄 将PostModel转换为ActivityModel（用于分享服务）
  ActivityModel _convertToActivityModel(PostModel postModel) {
    try {
      developer.log('🔄 开始转换PostModel到ActivityModel');
      
      // 解析活动时间
      DateTime activityDate;
      if (postModel.activityPublishTime?.isNotEmpty == true) {
        try {
          activityDate = DateTime.parse(postModel.activityPublishTime!);
        } catch (e) {
          // 如果解析失败，使用当前时间加一天作为默认
          activityDate = DateTime.now().add(const Duration(days: 1));
        }
      } else if (postModel.publishTime?.isNotEmpty == true) {
        try {
          activityDate = DateTime.parse(postModel.publishTime!);
        } catch (e) {
          activityDate = DateTime.now().add(const Duration(days: 1));
        }
      } else {
        activityDate = DateTime.now().add(const Duration(days: 1));
      }
      
      // 创建组织者信息
      final organizer = UserModel(
        id: postModel.authorId?.toString() ?? '0',
        name: postModel.authorName,
        avatarUrl: postModel.authorAvatar.isNotEmpty ? postModel.authorAvatar : '',
      );
      
      // 获取活动图片
      final imageUrl = postModel.images.isNotEmpty ? postModel.images.first : '';
      
      // 获取活动标签
      final tags = postModel.activityTags ?? ['活动'];
      
      final activityModel = ActivityModel(
        id: postModel.id,
        title: postModel.title,
        description: postModel.content.isNotEmpty ? postModel.content : '精彩活动等你参加！',
        location: postModel.location ?? '待定',
        date: activityDate,
        imageUrl: imageUrl,
        organizer: organizer,
        participants: postModel.currentParticipants ?? 0,
        maxParticipants: postModel.maxParticipants ?? 10,
        tags: tags,
      );
      
      developer.log('✅ PostModel转换为ActivityModel成功');
      developer.log('📝 转换后的活动: ${activityModel.title}');
      
      return activityModel;
      
    } catch (e) {
      developer.log('❌ PostModel转换失败: $e');
      // 返回一个基础的ActivityModel作为fallback
      return ActivityModel(
        id: postModel.id,
        title: postModel.title,
        description: postModel.content.isNotEmpty ? postModel.content : '精彩活动等你参加！',
        location: postModel.location ?? '待定',
        date: DateTime.now().add(const Duration(days: 1)),
        imageUrl: postModel.images.isNotEmpty ? postModel.images.first : '',
        organizer: UserModel(
          id: postModel.authorId?.toString() ?? '0',
          name: postModel.authorName,
          avatarUrl: postModel.authorAvatar,
        ),
        participants: 0,
        maxParticipants: 10,
        tags: ['活动'],
      );
    }
  }

  /// 分享活动 - 升级版本，支持动态分享页面
  void _shareActivity() async {
    try {
      developer.log('🔗 开始分享活动: ${widget.activity.title}');
      
      // 获取原生微信分享服务
      final weChatShareService = Get.find<NativeWeChatShareService>();
      
      // 🔄 将PostModel转换为ActivityModel
      final activityModel = _convertToActivityModel(widget.activity);
      
      // 🎨 使用新的活动分享页面系统
      final success = await weChatShareService.shareActivityWithPage(
        activity: activityModel,
      );
      
      if (success) {
        developer.log('✅ 活动分享页面生成成功');
      } else {
        developer.log('❌ 活动分享页面生成失败，使用降级方案');
        
        // 降级到原来的分享方式
        await _shareActivityFallback();
      }
      
    } catch (e) {
      developer.log('💥 分享活动异常: $e');
      ToastUtil.error('分享功能暂时不可用: $e');
      
      // 尝试降级分享
      await _shareActivityFallback();
    }
  }
  
  /// 降级分享方案（原来的分享方式）
  Future<void> _shareActivityFallback() async {
    try {
      developer.log('🔄 使用降级分享方案...');
      
      final weChatShareService = Get.find<NativeWeChatShareService>();
      
      // 准备分享内容
      final title = widget.activity.title;
      final description = '我在玩真的发现了一个有趣的活动，快来看看吧！';
      
      // 生成分享链接
      final shareUrl = await weChatShareService.generateShareUrl(
        widget.activity.id.toString()
      );
      
      // 获取活动图片作为缩略图
      String? thumbUrl;
      if (widget.activity.images.isNotEmpty) {
        thumbUrl = widget.activity.images.first;
      }
      
      developer.log('📝 降级分享 - 标题: $title');
      developer.log('📝 降级分享 - 描述: $description');
      developer.log('🌐 降级分享 - 链接: $shareUrl');
      developer.log('🖼️ 降级分享 - 缩略图: ${thumbUrl ?? "无"}');
      
      // 显示微信分享选择对话框
      weChatShareService.showWeChatShareDialog(
        title: title,
        description: description,
        webUrl: shareUrl,
        thumbUrl: thumbUrl,
      );
      
    } catch (e) {
      developer.log('💥 降级分享也失败了: $e');
      ToastUtil.error('分享功能暂时不可用');
    }
  }
  
  /// 跳转到用户信息页面
  void _goToUserProfile() async {
    developer.log('🔗 点击头像，跳转到用户信息页面: ${widget.activity.authorName}');
    
    try {
      // 获取发布者ID
      int publisherId;
      if (widget.activity.authorId != null) {
        publisherId = widget.activity.authorId!;
      } else {
        // 尝试从活动ID中提取发布者ID（兜底方案）
        final activityIdStr = widget.activity.id.replaceFirst('real_activity_', '');
        final activityId = int.tryParse(activityIdStr);
        if (activityId == null) {
          ToastUtil.error('无法获取用户信息');
          return;
        }
        // 这里应该有更好的方式获取发布者ID，暂时使用活动ID
        publisherId = activityId;
      }
      
      developer.log('👤 开始获取用户信息，发布者ID: $publisherId');
      
      // 显示加载提示
      Get.dialog(
        const Center(
          child: CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFE33641)),
          ),
        ),
        barrierDismissible: false,
      );
      
      // 调用用户过滤内容API获取用户信息
      final userResponse = await UserApi.getUserFilteredContent(
        userId: publisherId,
        contentType: 'activities', // 先获取活动信息
      );
      
      // 关闭加载对话框
      Get.back();
      
      if (userResponse.isSuccess && userResponse.user != null) {
        final user = userResponse.user!;
        developer.log('✅ 成功获取用户信息: ${user.username}');
        
        // 将FilteredUserInfo转换为用户信息页面需要的参数
        final userInfo = {
          'userId': user.userid,
          'username': user.username,
          'avatar': user.userAvatarUrl ?? '',
          'signature': user.userSignature ?? '',
          'userLevel': user.userLevel ?? 0,
          'userFollowers': user.userFollowers ?? 0,
          'userLikes': user.userLikes ?? 0,
          'userPoints': user.userPoints ?? 0, // 🔥 添加积分字段支持（修复等级显示问题）
          'userTags': user.userTags ?? [],
          'userHobbies': user.userHobbies ?? [],
          'userFrequentPlaces': user.userFrequentPlaces ?? '未知',
          'userCity': user.userCity ?? '未知',
          'userImgUrls': user.userImgUrls ?? [],
          'activities': userResponse.activities ?? [], // 这里已经是 List<ActivityData>
          'friendCount': userResponse.friendCount ?? 0,
        };
        
        // 跳转到用户信息页面
        Get.toNamed(
          RouteNames.myUserInfo,
          arguments: userInfo,
        );
        
        developer.log('✅ 用户信息页面跳转完成');
      } else {
        developer.log('❌ 获取用户信息失败: ${userResponse.message}');
        ToastUtil.error('获取用户信息失败: ${userResponse.message ?? "未知错误"}');
      }
      
    } catch (e) {
      // 关闭可能的加载对话框
      if (Get.isDialogOpen == true) {
        Get.back();
      }
      developer.log('💥 获取用户信息异常: $e');
      ToastUtil.error('获取用户信息失败');
    }
  }
  
  /// 提交举报（与MyApplication2保持一致的参数格式）
  Future<void> _submitReport(String reportText, String selectedReason) async {
    try {
      developer.log('🚩 开始提交举报');
      developer.log('📝 举报内容: $reportText');
      developer.log('📝 选择原因: $selectedReason');
      
      // 获取当前用户
      final currentUser = userService.currentUser;
      if (currentUser == null) {
        ToastUtil.error('请先登录');
        return;
      }
      
      // 从活动ID中提取数字ID
      final activityIdStr = widget.activity.id.replaceFirst('real_activity_', '');
      final activityId = int.tryParse(activityIdStr);
      
      if (activityId == null) {
        ToastUtil.error('活动ID格式错误');
        return;
      }
      
      ToastUtil.info('正在提交举报...');
      
      // 🔥 使用与MyApplication2一致的参数格式
      final result = await _submitReportWithMyApp2Format(
        reporterId: currentUser.userid,
        contentId: activityId,
        reportReason: reportText, // 使用用户输入的完整内容
      );
      
      if (result['success'] == true) {
        developer.log('✅ 举报提交成功');
        ToastUtil.success('举报成功，我们会尽快处理');
      } else {
        developer.log('❌ 举报提交失败: ${result['message']}');
        ToastUtil.error('举报失败: ${result['message']}');
      }
      
    } catch (e) {
      developer.log('💥 提交举报异常: $e');
      ToastUtil.error('举报提交失败，请重试');
    }
  }
  
  /// 与MyApplication2保持一致的举报提交方法
  Future<Map<String, dynamic>> _submitReportWithMyApp2Format({
    required int reporterId,
    required int contentId,
    required String reportReason,
  }) async {
    try {
      developer.log('🔄 =============== 开始举报活动（MyApplication2格式） ===============');
      developer.log('🎯 举报者ID: $reporterId');
      developer.log('🎯 活动ID: $contentId');
      developer.log('🎯 举报原因: $reportReason');

      // 🔥 构建与MyApplication2完全一致的请求参数
      final requestData = <String, dynamic>{
        'reportType': '活动',                    // 固定字符串 "活动"
        'reporterId': reporterId.toString(),    // 字符串格式的用户ID
        'contentId': contentId,                 // 活动ID
        'reportReason': reportReason,           // 举报内容
        'timestamp': DateTime.now().millisecondsSinceEpoch ~/ 1000, // 时间戳
      };

      developer.log('📊 请求参数（MyApplication2格式）: $requestData');
      
      // 🔥 使用AES加密（与MyApplication2保持一致）
      developer.log('🔐 开始AES加密举报数据...');
      
      // 使用 EncryptionUtil 创建加密载荷
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      developer.log('🚀 准备发送加密请求到: /reports/create/');

      // 发送请求
      final response = await HttpService.to.post(
        '/reports/create/',
        data: encryptedPayload,
      );

      developer.log('📨 举报响应: $response');

      // 检查响应状态
      if (response is Map<String, dynamic> && response['status'] == 'success') {
        developer.log('✅ 举报提交成功: ${response['message']}');
        return {
          'success': true,
          'message': response['message'] ?? '举报提交成功',
        };
      } else {
        String errorMessage = '举报提交失败';
        if (response is Map<String, dynamic> && response['message'] != null) {
          errorMessage = response['message'];
        }
        developer.log('❌ 举报提交失败: $errorMessage');
        return {
          'success': false,
          'message': errorMessage,
        };
      }

    } catch (e) {
      developer.log('💥 举报活动异常: $e');
      return {
        'success': false,
        'message': '举报提交失败: ${e.toString()}',
      };
    }
  }
  
  /// 获取按钮文本（使用timeAgo字段保持与活动列表一致）
  String _getButtonText() {
    if (isCurrentUserActivity) {
      return '这是我发布的活动';
    } else if (isJoined) {
      return '已加入活动 ($joinedCount人已参与)';
    } else {
      // 🎯 修复：使用timeAgo字段保持与活动列表显示一致
      if (widget.activity.timeAgo.contains('/')) {
        // 直接使用timeAgo中的人数信息
        final timeAgoText = widget.activity.timeAgo.replaceAll('人', '');
        return '我要加入 (${timeAgoText}人)';
      } else {
        // 兜底：使用解析的人数
        final maxPeople = widget.activity.maxParticipants ?? 0;
        final currentPeople = joinedCount;
        return '我要加入 ($currentPeople/${maxPeople}人)';
      }
    }
  }
  
  /// 🗺️ 地图底部弹出框 - 打开外部地图应用
  void _openLocationInMap() {
    final location = widget.activity.location;
    final latitude = widget.activity.latitude;
    final longitude = widget.activity.longitude;
    
    if (location?.isNotEmpty != true) {
      ToastUtil.warning('位置信息不完整');
      return;
    }
    
    developer.log('🗺️ 准备显示地图底部弹出框');
    developer.log('📍 位置: $location');
    developer.log('🌐 坐标: $latitude, $longitude');
    
    // 🎯 显示地图底部弹出框
    Get.bottomSheet(
      Container(
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 🎨 顶部指示器
            Container(
              margin: const EdgeInsets.only(top: 8, bottom: 16),
              width: 40,
              height: 4,
              decoration: BoxDecoration(
                color: Colors.grey[300],
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            
            // 🎨 标题区域
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
              child: Row(
                children: [
                  Container(
                    padding: const EdgeInsets.all(8),
                    decoration: BoxDecoration(
                      color: const Color(0xFFE33641).withOpacity(0.1),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: const Icon(
                      Icons.map,
                      color: Color(0xFFE33641),
                      size: 24,
                    ),
                  ),
                  const SizedBox(width: 12),
                  const Expanded(
                    child: Text(
                      '打开地图',
                      style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                        color: Colors.black87,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            
            // 🎨 位置信息展示
            Container(
              margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.grey[50],
                borderRadius: BorderRadius.circular(12),
                border: Border.all(color: Colors.grey[200]!),
              ),
              child: Row(
                children: [
                  Icon(Icons.location_on, color: Colors.grey[600], size: 20),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      location!,
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.grey[700],
                        height: 1.4,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            
            const SizedBox(height: 8),
            
            // 🗺️ 打开手机地图按钮
            Container(
              margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 4),
              width: double.infinity,
              child: ElevatedButton(
                onPressed: () async {
                  Get.back(); // 关闭底部弹出框
                  await _openExternalMap();
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFFE33641),
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                  elevation: 0,
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Icon(
                      Icons.launch_rounded,
                      size: 20,
                    ),
                    const SizedBox(width: 8),
                    const Text(
                      '打开手机地图',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ],
                ),
              ),
            ),
            
            const SizedBox(height: 24),
            
            // 🎨 取消按钮
            Container(
              margin: const EdgeInsets.symmetric(horizontal: 20),
              width: double.infinity,
              child: TextButton(
                onPressed: () => Get.back(),
                style: TextButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  backgroundColor: Colors.grey[100],
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
                child: const Text(
                  '取消',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                    color: Colors.grey,
                  ),
                ),
              ),
            ),
            
            // 🎨 底部安全区域
            SizedBox(height: MediaQuery.of(Get.context!).padding.bottom + 16),
          ],
        ),
      ),
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
    );
  }
  
  /// 🌍 打开外部地图应用
  Future<void> _openExternalMap() async {
    try {
      final location = widget.activity.location!;
      final latitude = widget.activity.latitude ?? 0.0;
      final longitude = widget.activity.longitude ?? 0.0;
      
      developer.log('🌍 准备打开外部地图应用');
      developer.log('📍 位置: $location');
      developer.log('🌐 坐标: $latitude, $longitude');
      
      // 🚀 使用地图启动器工具类
      await MapLauncherUtil.openMapLocation(
        latitude: latitude,
        longitude: longitude,
        locationName: location,
        title: widget.activity.title,
      );
      
    } catch (e) {
      developer.log('💥 打开外部地图失败: $e');
      ToastUtil.error('打开外部地图失败');
    }
  }
  

  


  @override
  Widget build(BuildContext context) {
    // 使用MediaQuery安全地获取屏幕高度
    final screenHeight = MediaQuery.of(context).size.height;
    // 使用安全的计算方式，避免可能的NaN或Infinity
    final sheetHeight = screenHeight > 0 ? screenHeight * 0.9 : 500.0;
    
    return SizedBox(
      height: sheetHeight,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // 主要内容区域
          Expanded(
            child: SingleChildScrollView(
              physics: const BouncingScrollPhysics(),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 图片区域和用户信息 - 横向显示
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 图片 - 占据左侧主要空间
                      if (widget.activity.images.isNotEmpty)
                        Expanded(
                          flex: 4,
                          child: Padding(
                            padding: const EdgeInsets.fromLTRB(12, 12, 0, 0),
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(12),
                              child: AspectRatio(
                                aspectRatio: 1.2, // 🔥 统一使用1.2比例，避免拉伸
                                child: Stack(
                                  children: [
                                    // 图片切换区域
                                    PageView.builder(
                                      controller: _imagePageController,
                                      onPageChanged: (index) {
                                        setState(() {
                                          _currentImageIndex = index;
                                        });
                                      },
                                      itemCount: widget.activity.images.length,
                                      itemBuilder: (context, index) {
                                        return CachedNetworkImage(
                                          imageUrl: widget.activity.images[index],
                                          fit: BoxFit.cover,
                                          placeholder: (context, url) => Container(
                                            color: Colors.grey[50],
                                            // 移除loading动画，直接显示空白背景
                                          ),
                                          errorWidget: (context, url, error) => Container(
                                            color: Colors.grey[300],
                                            child: const Icon(Icons.image_not_supported, size: 50),
                                          ),
                                          // 缓存配置 - 提升加载速度
                                          memCacheWidth: 600,  // 内存缓存宽度
                                          memCacheHeight: 450, // 内存缓存高度 (4:3比例)
                                          maxWidthDiskCache: 600, // 磁盘缓存最大宽度
                                          maxHeightDiskCache: 450, // 磁盘缓存最大高度
                                        );
                                      },
                                    ),
                                    // 图片指示器
                                    if (widget.activity.images.length > 1)
                                      Positioned(
                                        bottom: 12,
                                        left: 0,
                                        right: 0,
                                        child: Row(
                                          mainAxisAlignment: MainAxisAlignment.center,
                                          children: widget.activity.images.asMap().entries.map((entry) {
                                            return GestureDetector(
                                              onTap: () {
                                                _imagePageController.animateToPage(
                                                  entry.key,
                                                  duration: const Duration(milliseconds: 300),
                                                  curve: Curves.ease,
                                                );
                                              },
                                              child: Container(
                                                width: 8.0,
                                                height: 8.0,
                                                margin: const EdgeInsets.symmetric(horizontal: 4.0),
                                                decoration: BoxDecoration(
                                                  shape: BoxShape.circle,
                                                  color: _currentImageIndex == entry.key
                                                      ? Colors.white
                                                      : Colors.white.withOpacity(0.4),
                                                  boxShadow: [
                                                    BoxShadow(
                                                      color: Colors.black.withOpacity(0.3),
                                                      blurRadius: 3,
                                                      offset: const Offset(0, 1),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                            );
                                          }).toList(),
                                        ),
                                      ),
                                  ],
                                ),
                              ),
                            ),
                          ),
                        )
                      else
                        Expanded(
                          flex: 4,
                          child: Padding(
                            padding: const EdgeInsets.fromLTRB(12, 12, 0, 0),
                            child: Container(
                              decoration: BoxDecoration(
                                color: Colors.grey[100],
                                borderRadius: BorderRadius.circular(12),
                              ),
                              child: AspectRatio(
                                aspectRatio: 4/3,
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Icon(Icons.photo, size: 40, color: Colors.grey[400]),
                                    const SizedBox(height: 8),
                                    Text(
                                      '暂无图片',
                                      style: TextStyle(color: Colors.grey[600], fontSize: 12),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ),
                        ),
                      
                      // 用户信息
                      Container(
                        width: 80,
                        padding: const EdgeInsets.all(12.0),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            // 💡 头像可点击，跳转到用户信息页面
                            GestureDetector(
                              onTap: _goToUserProfile,
                              child: widget.activity.authorAvatar.isNotEmpty && widget.activity.authorAvatar.startsWith('http') // 🔥 修复：检查是否为有效URL
                                  ? ClipOval(
                                      child: CachedNetworkImage(
                                        imageUrl: widget.activity.authorAvatar,
                                        width: 50,
                                        height: 50,
                                        fit: BoxFit.cover,
                                        placeholder: (context, url) => Container(
                                          width: 50,
                                          height: 50,
                                          color: Colors.grey[200],
                                          child: const Icon(Icons.person, size: 30, color: Colors.grey),
                                        ),
                                        errorWidget: (context, url, error) => Container(
                                          width: 50,
                                          height: 50,
                                          color: Colors.grey[200],
                                          child: const Icon(Icons.person, size: 30, color: Colors.grey),
                                        ),
                                        // 缓存配置
                                        memCacheWidth: 100,
                                        memCacheHeight: 100,
                                        maxWidthDiskCache: 100,
                                        maxHeightDiskCache: 100,
                                      ),
                                    )
                                  : CircleAvatar( // 🔥 修复：对于空URL或无效URL显示默认头像
                                      radius: 25,
                                      backgroundColor: Colors.grey[200],
                                      child: const Icon(Icons.person, size: 30, color: Colors.grey),
                                    ),
                            ),
                            const SizedBox(height: 8),
                            // 💡 昵称也可点击
                            GestureDetector(
                              onTap: _goToUserProfile,
                              child: Text(
                                widget.activity.authorName,
                                style: const TextStyle(
                                  fontSize: 12,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.black,
                                ),
                              ),
                            ),
                            const SizedBox(height: 6),
                            // 守护者标签
                            Container(
                              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                              decoration: BoxDecoration(
                                color: const Color(0xFFE33641),
                                borderRadius: BorderRadius.circular(10),
                              ),
                              child: const Text(
                                '守护者',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 10,
                                ),
                              ),
                            ),
                            const SizedBox(height: 8),
                            // 加好友按钮 - 只有在不是好友且不是自己的活动时才显示
                            if (!isCurrentUserActivity && !_isFriend)
                              if (_isCheckingFriendship)
                                // 检查中显示加载指示器
                                Container(
                                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                                  child: SizedBox(
                                    width: 16,
                                    height: 16,
                                    child: CircularProgressIndicator(
                                      strokeWidth: 2,
                                      valueColor: AlwaysStoppedAnimation<Color>(
                                        Color(0xFFE33641),
                                      ),
                                    ),
                                  ),
                                )
                              else
                                // 不是好友时显示加好友按钮
                                GestureDetector(
                                  onTap: _isAddingFriend ? null : _addFriend,
                                  child: Container(
                                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                                    decoration: BoxDecoration(
                                      color: _isAddingFriend 
                                          ? Colors.grey[400] 
                                          : const Color(0xFFE33641),
                                      borderRadius: BorderRadius.circular(15),
                                      boxShadow: [
                                        BoxShadow(
                                          color: Colors.black.withOpacity(0.1),
                                          blurRadius: 4,
                                          offset: const Offset(0, 2),
                                        ),
                                      ],
                                    ),
                                    child: _isAddingFriend
                                        ? SizedBox(
                                            width: 12,
                                            height: 12,
                                            child: CircularProgressIndicator(
                                              strokeWidth: 2,
                                              valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                                            ),
                                          )
                                        : const Text(
                                            '加好友',
                                            style: TextStyle(
                                              color: Colors.white,
                                              fontSize: 11,
                                              fontWeight: FontWeight.w500,
                                            ),
                                          ),
                                  ),
                                ),
                          ],
                        ),
                      ),
                    ],
                  ),
                  
                  // 标题和按钮区域
                  Padding(
                    padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
                    child: Row(
                      children: [
                        // 标题
                        Expanded(
                          child: Text(
                            widget.activity.title,
                            style: const TextStyle(
                              fontSize: 20,
                              fontWeight: FontWeight.bold,
                            ),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        const SizedBox(width: 8),
                        // 举报按钮
                        GestureDetector(
                          onTap: _showReportDialog,
                          child: Container(
                            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                            decoration: BoxDecoration(
                              color: const Color(0xFFE33641),
                              borderRadius: BorderRadius.circular(4),
                            ),
                            child: const Text(
                              '举报',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 12,
                              ),
                            ),
                          ),
                        ),
                        const SizedBox(width: 8),
                        // 分享按钮
                        GestureDetector(
                          onTap: _shareActivity,
                          child: const Icon(
                            Icons.share,
                            size: 20,
                            color: Colors.grey,
                          ),
                        ),
                      ],
                    ),
                  ),
                  
                  // 地址信息
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                    child: GestureDetector(
                      onTap: () => _openLocationInMap(), // 🗺️ 点击跳转到地图导航
                      child: Row(
                        children: [
                          const Icon(Icons.location_on, size: 16, color: Colors.grey),
                          const SizedBox(width: 4),
                          Expanded(
                            child: Text(
                              widget.activity.location?.isNotEmpty == true 
                                  ? widget.activity.location! 
                                  : (widget.activity.content.isNotEmpty 
                                      ? widget.activity.content 
                                      : '暂无地址信息'),
                              style: TextStyle(
                                fontSize: 12,
                                color: widget.activity.location?.isNotEmpty == true 
                                    ? const Color(0xFFE33641) // 🎨 有位置信息时显示红色，表示可点击
                                    : Colors.grey[600],
                                decoration: widget.activity.location?.isNotEmpty == true 
                                    ? TextDecoration.underline // 🎨 添加下划线表示可点击
                                    : TextDecoration.none,
                              ),
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  
                  // 时间信息
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                    child: Row(
                      children: [
                        const Icon(Icons.access_time, size: 16, color: Colors.grey),
                        const SizedBox(width: 4),
                        Text(
                          _getFormattedPublishTime(),
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.grey[600],
                          ),
                        ),
                      ],
                    ),
                  ),
                  
                  const SizedBox(height: 16),
                  
                  // 活动详情标题
                  const Padding(
                    padding: EdgeInsets.symmetric(horizontal: 16),
                    child: Text(
                      '活动详情',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  
                  const SizedBox(height: 12),
                  
                  
                  // 活动信息
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            const Text('参与人数：', style: TextStyle(fontSize: 14)),
                            Text(
                              // 🎯 修复：使用timeAgo字段保持与活动列表显示一致
                              widget.activity.timeAgo.contains('/') 
                                  ? widget.activity.timeAgo
                                  : (widget.activity.currentParticipants != null && widget.activity.maxParticipants != null
                                      ? '${widget.activity.currentParticipants}/${widget.activity.maxParticipants}人'
                                      : '暂无'),
                              style: const TextStyle(fontSize: 14),
                            ),
                          ],
                        ),
                        const SizedBox(height: 8),
                        Row(
                          children: [
                            const Text('消费：', style: TextStyle(fontSize: 14)),
                            Text(widget.activity.paymentType.isNotEmpty ? widget.activity.paymentType : '待商议', 
                                style: const TextStyle(fontSize: 14)),
                          ],
                        ),
                        const SizedBox(height: 8),
                        Row(
                          children: [
                            const Text('性别：', style: TextStyle(fontSize: 14)), // 修改文本
                            Text(
                              // 根据activityRestriction显示性别限制
                              widget.activity.activityRestriction?.isNotEmpty == true
                                  ? widget.activity.activityRestriction!.join(', ')
                                  : '无限制',
                              style: const TextStyle(fontSize: 14),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                  
                  const SizedBox(height: 16),
                  
                  // 详细描述
                  const Padding(
                    padding: EdgeInsets.symmetric(horizontal: 16),
                    child: Text(
                      '详细描述',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  
                  const SizedBox(height: 8),
                  
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 16),
                    child: Text(
                      widget.activity.content.isNotEmpty 
                          ? widget.activity.content 
                          : '暂无详细描述',
                      style: const TextStyle(
                        fontSize: 14,
                        color: Colors.black87,
                      ),
                    ),
                  ),
                  
                  const SizedBox(height: 20),
                ],
              ),
            ),
          ),
          
          // 底部加入按钮
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.05),
                  blurRadius: 4,
                  offset: const Offset(0, -2),
                ),
              ],
            ),
            child: SizedBox(
              width: double.infinity,
              child: ElevatedButton(
                onPressed: _isJoining ? null : _joinActivity,
                style: ElevatedButton.styleFrom(
                  backgroundColor: isCurrentUserActivity 
                      ? Colors.grey[400] 
                      : (isJoined ? Colors.green : const Color(0xFFE33641)),
                  disabledBackgroundColor: Colors.grey[300],
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                ),
                child: _isJoining
                    ? const SizedBox(
                        width: 20,
                        height: 20,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                        ),
                      )
                    : Text(
                        _getButtonText(),
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
